import os

from utils import doc_util, html_util, json_util, date_util, read_config as config, excel_util, price_util
from service import score_service, data_service
from methods import d月macd穿过0方法验证 as month_macd_service

result_path = os.path.join(config.data_path, 'result', '突破均线')
users_path = os.path.join(config.data_path, 'common', 'users')
config_path = os.path.join(config.data_path, 'common', 'config')
trigger_logs_path = os.path.join(config.data_path, 'logs', '突破均线任务1')


# macd + ave 跑批历史数据验证
def record_validation(stock_code, size):
    # 按照季度拆分
    log_list = doc_util.get_doc_str_list(os.path.join(trigger_logs_path, 'out.log'))
    record_dict = {}
    stock_name = data_service.stock(stock_code)['name']
    for log in log_list:
        if log[0:15] != 'triggerthedeal:':
            continue
        stock_info = json_util.info_to_json(log.split('triggerthedeal:')[1])
        code = stock_info['code']
        if code not in record_dict.keys():
            record_dict[code] = []
        record_dict[code].append(stock_info)
    for code in record_dict.keys():
        content_arr = []
        capital_hold = 0  # 持仓资金
        capital_idle = 100000  # 闲置资金
        hand_hold = 0  # 闲置资金
        last_deal_date = ''
        name = data_service.stock(code)['name']
        # path = os.path.join(result_path, date_util.get_date_str(), '记录认证', name + '-' + code + '.xlsx')
        # if os.path.exists(path):
        #     continue
        content_arr.append(['编码', '名称', '日期', '触发时间', '当前价格', '五日均线', '十日均线',
                            '触发标志', 'MACD', '超大单净流入', '大单净流入', '换手率', '持有手数', '持仓金额',
                            '闲置金额', '总金额'])
        s_log_list = record_dict[code]
        for stock_info in s_log_list:
            if stock_info['code'] == code:
                deal_price = stock_info['rt_price']  # 当前价格
                deal_time = stock_info['deal_time']  # 交易时间
                deal_date = deal_time[0:10]  # 交易日期
                if deal_date == last_deal_date:
                    print('同一天多次触发')
                    continue
                last_deal_date = deal_date
                # 交易标志 deal_flag = 0  # 1:加仓 2:入仓 3:清仓 4:减仓
                deal_flag = 0
                if 'deal_flag' in stock_info.keys():
                    deal_flag = stock_info['deal_flag']
                buy_sell_flag = 0
                # buy_sell_flag = 0  # 1买入 -1卖出
                # 交易标志 deal_flag = 0  # 1:全仓 2:加半仓 3:清仓 4:减半仓
                if deal_flag == 1 or deal_flag == 2:  # 买入
                    buy_sell_flag = 1
                    deal_capital = capital_idle
                    if hand_hold == 0 and deal_flag == 2:
                        deal_capital = int(deal_capital / 2)
                    deal_hand = int(deal_capital / (deal_price * 100))
                    if deal_hand == 0:  # 如果可购买数量为0 返回结果
                        continue
                elif deal_flag == 3 or deal_flag == 4:  # 卖出
                    buy_sell_flag = -1
                    if hand_hold != 0:
                        deal_hand = int(capital_idle / (deal_price * 100))
                        if deal_hand == 0 and deal_flag == 4:  # 全仓状态
                            deal_hand = int(hand_hold / 2)
                        else:  # 清仓
                            deal_hand = hand_hold
                    else:
                        continue
                else:
                    continue
                hand_hold = hand_hold + deal_hand * buy_sell_flag
                deal_amt = round(deal_hand * deal_price * 100, 2)  # 成交金额
                deal_tax = round(deal_amt * 0.00025, 2)  # 印花税
                capital_hold = round(hand_hold * deal_price * 100, 2)
                capital_idle = round(capital_idle - deal_amt * buy_sell_flag - deal_tax, 2)
                data = []
                data.append(code)
                data.append(name)
                data.append(deal_date)
                data.append(deal_time)
                data.append(deal_price)
                data.append(str(stock_info['ave5']))
                data.append(str(stock_info['ave10']))
                if 'result_file_path' not in stock_info.keys():
                    data.append('未归类')
                else:
                    data.append(stock_info['result_file_path'])
                data.append(stock_info['macd'])
                if 'sb_io' in stock_info.keys():
                    data.append(str(stock_info['sb_io']))
                    data.append(str(stock_info['b_io']))
                    data.append(str(stock_info['hsl']))
                else:
                    data.append('无记录')
                    data.append('无记录')
                    data.append('无记录')
                data.append(str(hand_hold))
                data.append(str(capital_hold))
                data.append(str(capital_idle))
                data.append(str(round(capital_hold + capital_idle, 2)))
                content_arr.append(data)
        excel_util.gen_an_excel(os.path.join(result_path, date_util.get_date_str(), '记录认证'), name + '-' + code, '',
                                content_arr)
    path = os.path.join(result_path, date_util.get_date_str(), '记录认证', stock_name + '-' + stock_code + '.xlsx')
    path = path.replace('\\', '*').replace('/', '*')
    file_url = 'http://' + config.domain + '/download/doc/' + path
    return html_util.get_button_href(file_url, '点击下载验证结果')


# macd + ave 跑批历史数据验证
def record_validation_v1(stock_code, size):
    # 按照季度拆分
    log_list = doc_util.get_doc_str_list(os.path.join(trigger_logs_path, 'out.log'))
    record_dict = {}
    stock_name = data_service.stock(stock_code)['name']
    for log in log_list:
        if log[0:15] != 'triggerthedeal:':
            continue
        stock_info = json_util.info_to_json(log.split('triggerthedeal:')[1])
        code = stock_info['code']
        if code not in record_dict.keys():
            record_dict[code] = []
        record_dict[code].append(stock_info)
    for code in record_dict.keys():
        content_arr = []
        capital_hold = 0  # 持仓资金
        capital_idle = 100000  # 闲置资金
        hand_hold = 0  # 闲置资金
        last_deal_date = ''
        name = data_service.stock(code)['name']
        # path = os.path.join(result_path, date_util.get_date_str(), '记录认证', name + '-' + code + '.xlsx')
        # if os.path.exists(path):
        #     continue
        content_arr.append(['编码', '名称', '日期', '触发时间', '当前价格', '五日均线', '十日均线',
                            '触发标志', 'MACD', '超大单净流入', '大单净流入', '换手率', '持有手数', '持仓金额',
                            '闲置金额', '总金额'])
        s_log_list = record_dict[code]
        for stock_info in s_log_list:
            if stock_info['code'] == code:
                deal_price = stock_info['rt_price']  # 当前价格
                deal_time = stock_info['deal_time']  # 交易时间
                deal_date = deal_time[0:10]  # 交易日期
                if deal_date == last_deal_date:
                    print('同一天多次触发')
                    continue
                if 'sb_io' not in stock_info.keys():
                    continue
                sb_io = stock_info['sb_io']
                b_io = stock_info['b_io']
                hsl = stock_info['hsl']
                # 交易标志 deal_flag = 0  # 1:加仓 2:入仓 3:清仓 4:减仓
                deal_flag = 0
                if 'deal_flag' in stock_info.keys():
                    deal_flag = stock_info['deal_flag']
                buy_sell_flag = 0
                # buy_sell_flag = 0  # 1买入 -1卖出
                # 交易标志 deal_flag = 0  # 1:全仓 2:加半仓 3:清仓 4:减半仓
                if deal_flag == 1 or deal_flag == 2:  # 买入
                    if sb_io + b_io < 0:  # 大单是流出的不买
                        continue
                    if hsl < 0.4:  # 换手率
                        continue
                    last_deal_date = deal_date
                    buy_sell_flag = 1
                    deal_capital = capital_idle
                    if hand_hold == 0 and deal_flag == 2:
                        deal_capital = int(deal_capital / 5)
                    deal_hand = int(deal_capital / (deal_price * 100))
                    if deal_hand == 0:  # 如果可购买数量为0 返回结果
                        continue
                elif deal_flag == 3 or deal_flag == 4:  # 卖出
                    last_deal_date = deal_date
                    buy_sell_flag = -1
                    if hand_hold != 0:
                        deal_hand = int(capital_idle / (deal_price * 100))
                        if deal_hand == 0 and deal_flag == 4:  # 全仓状态
                            deal_hand = int(hand_hold / 5)
                        else:  # 清仓
                            deal_hand = hand_hold
                    else:
                        continue
                else:
                    continue
                hand_hold = hand_hold + deal_hand * buy_sell_flag
                deal_amt = round(deal_hand * deal_price * 100, 2)  # 成交金额
                deal_tax = round(deal_amt * 0.00025, 2)  # 印花税
                capital_hold = round(hand_hold * deal_price * 100, 2)
                capital_idle = round(capital_idle - deal_amt * buy_sell_flag - deal_tax, 2)
                data = []
                data.append(code)
                data.append(name)
                data.append(deal_date)
                data.append(deal_time)
                data.append(deal_price)
                data.append(str(stock_info['ave5']))
                data.append(str(stock_info['ave10']))
                if 'result_file_path' not in stock_info.keys():
                    data.append('未归类')
                else:
                    data.append(stock_info['result_file_path'])
                data.append(stock_info['macd'])
                if 'sb_io' in stock_info.keys():
                    data.append(str(stock_info['sb_io']))
                    data.append(str(stock_info['b_io']))
                    data.append(str(stock_info['hsl']))
                else:
                    data.append('无记录')
                    data.append('无记录')
                    data.append('无记录')
                data.append(str(hand_hold))
                data.append(str(capital_hold))
                data.append(str(capital_idle))
                data.append(str(round(capital_hold + capital_idle, 2)))
                content_arr.append(data)
        excel_util.gen_an_excel(os.path.join(result_path, date_util.get_date_str(), '记录认证'), name + '-' + code, '',
                                content_arr)
    path = os.path.join(result_path, date_util.get_date_str(), '记录认证', stock_name + '-' + stock_code + '.xlsx')
    path = path.replace('\\', '*').replace('/', '*')
    file_url = 'http://' + config.domain + '/download/doc/' + path
    return html_util.get_button_href(file_url, '点击下载验证结果')


# 汇总验证结果
# content_arr.append(['编码', '名称', '日期', '触发时间', '当前价格', '五日均线', '十日均线',
#                             '触发标志', 'MACD', '超大单净流入', '大单净流入', '换手率', '持有手数', '持仓金额',
#                             '闲置金额', '总金额'])

# ['0编码', '1名称', '2日期', '3触发时间', '4当前价格', '5五日均线', '6十日均线',
#  '7触发标志', '8MACD', '9超大单净流入', '10大单净流入', '11换手率', '12持有手数',
#  '13持仓金额', '14闲置金额', '15总金额'])
def conclusion_record_validation():
    valid_path = os.path.join(result_path, date_util.get_date_str(), '记录认证')
    path_names = doc_util.get_file_names(valid_path)
    result_data = [['编码', '名称', '当前价格', '最高资金', '最低资金', '最高涨幅',
                    '最低涨幅', '价格涨幅', '资金涨幅', '最终资金', '最终利润']]
    for path_name in path_names:
        if path_name == '000000':
            continue
        content_arr = excel_util.get_excel_info(os.path.join(valid_path, path_name + '.xlsx'), '')
        rows_num = len(content_arr)
        if rows_num == 1: continue
        code = content_arr[1][0]
        name = content_arr[1][1]
        beg_price = content_arr[1][4]
        max_capital = 0
        min_capital = 99999999
        end_capital = 0
        rt_price = price_util.get_rt_p(code)
        for i in range(1, rows_num):
            row = content_arr[i]
            hand = int(row[12])
            idle_capital = float(row[14])
            all_capital = float(row[15])
            if i == rows_num - 1:
                all_capital = idle_capital + hand * rt_price * 100
                end_capital = all_capital
            if max_capital < all_capital:
                max_capital = all_capital
            if min_capital > all_capital:
                min_capital = all_capital
        data = []
        data.append(code)
        data.append(name)
        data.append(str(rt_price))
        data.append(str(max_capital))
        data.append(str(min_capital))
        data.append(str(round((max_capital - 100000) / 1000, 2)))
        data.append(str(round((min_capital - 100000) / 1000, 2)))
        data.append(str(round((rt_price - beg_price) / beg_price * 100, 2)))
        data.append(str(round((end_capital - 100000) / 1000, 2)))
        data.append(str(round(end_capital, 2)))
        data.append(str(round(end_capital - 100000, 2)))
        result_data.append(data)
    excel_util.gen_an_excel(valid_path, '000000', '', result_data)


if __name__ == '__main__':
    record_validation_v1('000157', 40)
    conclusion_record_validation()
